<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/18 14:57
 * Desc: 积分相关
 */
class Service_Api_Integral_Integral extends Contract_Api_Integral_Integral
{
    public function get_integral(int $mid): array
    {
        $member = DB::select('jifen','jifen_lottery_num')
            ->from('member')
            ->where('mid', '=', $mid)
            ->execute()
            ->current();
        return array(
            'jifen'       => $member['jifen'],
            'lottery_num' => $member['jifen_lottery_num'],
        );
    }

    function get_user_credit_list(int $mid, array $params = array()): array
    {
        /**
         * @var $page
         * @var $pagesize
         * @var int $type 类型:0-所有，1-使用，2-获得
         */
        extract($params);

        $log  = Model_Member_Jifen_Log::log_list($mid, $page, $pagesize, $type);
        $list = $log['list'];

        // 处理返回的积分列表数据
        foreach ($list as &$item) {
            $item['addtime']    = date('Y-m-d H:i', $item['addtime']);
            $item['point']      = $item['type'] == 1 ? '-' . $item['jifen'] : '+' . $item['jifen'];
            $item['jifen_type'] = $item['jifentype'];
            unset($item['memberid']);
            unset($item['jifentype']);
        }

        // 判断是否获取全部
        $total     = $log['total'];
        $now_num   = $pagesize * $page; // 当前获取总条数
        $completed = 0;//是否全部0-否，1-是
        if ($total <= $now_num) {
            $completed = 1;
        }

        return array(
            'list' => $list,
            'completed' => $completed,
            'total' => $total,
        );
    }

    public function get_integral_strategy(array $params): array
    {
        /**
         * @var $id
         * @var $type_id
         */
        extract($params);

        $main_table = DB::select('maintable')
            ->from('model')
            ->where('isopen', '=', 1)
            ->and_where('id', '=', $type_id)
            ->execute()
            ->get('maintable');

        if (empty($main_table)) {
            throw new Exception('未开启应用');
        }

        //产品信息
        $info = DB::select('jifentprice_id', 'jifenbook_id')
            ->from($main_table)
            ->where('id', '=', $id)
            ->execute()
            ->current();
        if (empty($info)) {
            throw new Exception('积分策略不存在');
        }

        // 积分抵现配置
        if ($type_id != 21) {
            $jifentprice_id = $info['jifentprice_id'];
        } else {
            //积分商城配置从系统配置表里面取
            $jifen_deduction = Model_Sysconfig::get_one_config('cfg_jifen_deduction');
            $jifentprice_id  = $jifen_deduction ? $jifen_deduction['value'] : '';
        }

        // 积分抵现
        $deduct = Model_Jifen_Price::get_used_jifentprice($jifentprice_id, $type_id);
        // 预定送积分
        $jifen_book = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], $type_id);
        //积分评论
        $jifen_comment = Model_Jifen::get_used_jifencomment($type_id);

        return array(
            'deduct' => $deduct,
            'jifen_book' => $jifen_book,
            'jifen_comment' => $jifen_comment
        );
    }

    function get_member_sign_status(int $mid): array
    {
        $member_sign = DB::select()
            ->from('member_sign')
            ->where('member_id', '=', $mid)
            ->and_where('sign_date', '=', strtotime(date('Ymd')))
            ->execute()
            ->current();

        //是否签到0-未签到，1-已签到
        return array(
            'status' => $member_sign ? 1 : 0
        );
    }

    function sign_in(int $mid): array
    {
        //最新一次签到记录
        $sign = DB::select('id', 'sign_date', 'sign_number')
            ->from('member_sign')
            ->where('member_id', '=', $mid)
            ->execute()
            ->current();

        //签到配置信息
        $sys_config = DB::select()
            ->from('sysconfig')
            ->where('varname', '=', 'cfg_sign_config')
            ->execute()
            ->current();
        $sys_config = unserialize($sys_config['value']);

        //每日签到积分数
        $list = array();
        foreach ($sys_config as $item) {
            $id     = explode('_', $item)[1];
            $list[] = array('jifen' => DB::select('value')
                ->from('jifen')
                ->where('id', '=', $id)
                ->execute()
                ->get('value'));
        }


        $result['data']['list'] = $list;
        $result['msg']          = '签到成功';
        //查询用户是否签到
        if (!$sign) {
            //未签到，新增签到
            $insertData = array(
                'member_id' => $mid,
                'sign_date' => strtotime(date('Ymd')),
                'sign_number' => 1,
            );
            list($bool, $rows) = DB::insert('member_sign', array_keys($insertData))->values(array_values($insertData))->execute();
            $index = 1;
        } elseif ($sign['sign_date'] < strtotime(date('Ymd') . ' -1 days')) {
            //未连续签到，重新签到
            $update['sign_number'] = 1;
            $update['sign_date']   = strtotime(date('Ymd'));
            $index                 = 1;
            $bool                  = DB::update('member_sign')->set($update)->where('member_id', '=', $mid)->execute();
        } elseif ($sign['sign_date'] == strtotime(date('Ymd') . ' -1 days')) {
            //连续签到
            $count = count($sys_config);
            //连续签到，计算签到周期
            $update['sign_number'] = ++$sign['sign_number'] % $count;
            $index                 = $update['sign_number'] == 0 ? $count : $update['sign_number'];
            $update['sign_number'] = $index;
            $update['sign_date']   = strtotime(date('Ymd'));
            $bool                  = DB::update('member_sign')->set($update)->where('member_id', '=', $mid)->execute();
        } else {
            //不需重新签到
            $sign['sign_number']       = intval($sign['sign_number']);
            $result['data']['current'] = $sign;
            $result['msg']             = '已签到';
            return $result;
        }

        //更新积分
        if (isset($bool) && $bool && isset($index) && isset($sys_config['item_attr_' . $index])) {
            $data = explode('_', $sys_config['item_attr_' . $index]);

            if (isset($data[1])) {
                $obj   = DB::select()->from('jifen')->where('id', '=', $data[1])->execute()->current();
                $jifen = Model_Jifen::reward_jifen($obj['label'], $mid);
                if ($jifen) {
                    $content = "会员签到获得{$jifen}积分";
                    St_Product::add_jifen_log($mid, $content, $jifen, 2);
                }
            }
        }

        //最新签到记录
        $sign = DB::select('id', 'sign_date', 'sign_number')
            ->from('member_sign')
            ->where('member_id', '=', $mid)
            ->execute()
            ->current();

        $sign['sign_number']       = intval($sign['sign_number']);
        $result['data']['current'] = $sign;
        return $result;
    }

    function integral_rank(int $mid): array
    {
        $member = DB::select('nickname','litpic','jifen')->from('member')->where('mid','=',$mid)->execute()->current();
        $info = Model_Member::member_rank($mid, array('return' => 'all'));
        $cfg_exchange_jifen    = intval(Model_Sysconfig::get_configs(0, 'cfg_exchange_jifen', true));
        if ($cfg_exchange_jifen) {
            $member['deductionPrice'] = floor($member['jifen'] / $cfg_exchange_jifen);
        } else {
            $member['deductionPrice'] = 0;
        }
        $member['allJifen'] = '';
        $member['currentRank'] = $info['current_rank'];

        return array(
            'member' => $member,
            'next' => $info['next'],
            'grade' => $info['grade']
        );
    }

    function get_grade_strategy(int $mid, array $params = array()): array
    {
        /**
         * @var int $type 1-首页三个任务，2-新手任务，3-每日任务
         */
        extract($params);

        switch ($type) {
            case 1:
                $strategy = Model_Api_V2_Integral::get_index_strategy();
                break;
            case 2:
                $strategy = Model_Api_V2_Integral::get_newbie_strategy($mid);
                break;
            case 3:
                $strategy = Model_Api_V2_Integral::get_daily_strategy($mid);
                break;
        }

        return array(
            'list' => $strategy
        );
    }

    function check_email(int $mid, string $email): array
    {
        // TODO: Implement check_email() method.
    }

    function send_email_code(int $mid, string $email): array
    {
        // TODO: Implement send_email_code() method.
    }

    function bind_email(int $mid, array $params = array()): array
    {
        // TODO: Implement bind_email() method.
    }
}